package gossip.v2.message;

import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import gossip.v2.util.SerializationUtils;
import gossip.v2.cluster.GossipNode;
import lombok.Getter;

// 用户消息
@Getter
@ProtobufClass
public class UserMessage extends GossipMessage {
    private String key;
    private byte[] value;

    public UserMessage() {
        type = Type.USER;
    }

    public UserMessage(GossipNode sender, String key, byte[] value) {
        this();
        setSender(sender);
        this.key = key;
        this.value = value;
    }

    public static UserMessage fromObject(GossipNode sender, String key, Object value) {
        return new UserMessage(sender, key, SerializationUtils.serialize(value));
    }

    private void setSender(GossipNode sender) {
        this.sender = sender;
        this.senderId = sender != null ? sender.getNodeId() : null;
    }

    public <T> T getValueAs(Class<T> clazz) {
        return SerializationUtils.deserialize(value, clazz);
    }

    public String getKey() { return key; }
    public byte[] getValue() { return value; }
}
